<template>
  <div class="app-container">
    <div>
      <p class="dialogTitle title">当前地震事件: 
        <span v-if="currentEvent">{{ currentEvent.eventName }}</span>
        <span v-else>请在地震事件管理中设置当前地震事件</span>
      </p>
    </div>

    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px" v-show="showSearch">
      <el-form-item label="类别" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择类别" clearable>
          <el-option v-for="item in option" :key="item.dictItemCode" :label="item.dictItemName" :value="item.dictItemCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="人员姓名" prop="personName">
          <el-input v-model="queryParams.personName" placeholder="请输入人员姓名"  clearable />
      </el-form-item>
      <el-form-item label="手机号" prop="tel">
          <el-input v-model="queryParams.tel" placeholder="请输入手机号"  clearable />
      </el-form-item>
      <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
            <el-button type="primary" :disabled="!currentEvent" @click="handleAdd">新建</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button plain   type="primary" :disabled="!currentEvent" @click="handleDel">批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button plain icon="Download" :disabled="!currentEvent" @click="handleImport">导入</el-button>
        </el-col>
        
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" refs="tableRef" :data="dataList" stripe @selection-change="handleSelectionChange" row-key="xpimId">
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column label="序号" align="center" width="55">
          <template #default="scope">
            <span>{{(queryParams.page - 1) * queryParams.rows + scope.$index + 1}}</span>
          </template>             
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="personName">
          <template #default="scope">
            <span style="color: #107ce1;cursor: pointer;" @click="handleEdit(scope.row)">{{ scope.row.personName }}</span>
          </template>   
        </el-table-column>
        <el-table-column label="性别" align="center" prop="gender" />
        <el-table-column label="类别" align="center" prop="category" >
        	<template #default="scope">					
	          {{getType(scope.row.category)}}
	        </template>
	      </el-table-column>
        <el-table-column label="手机号" align="center" prop="tel" />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">         
			      <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"   @pagination="getList" /> 
      
      <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="addRef" label-width="120px" :model="form" :rules="rules">
        <el-row style="margin: 20px 0;">  
          <!-- <el-col>
              <el-form-item label="省" prop="provinceId">
                <el-input v-model="form.provinceId" placeholder="请输入省"  clearable />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="市" prop="cityId">
                <el-input v-model="form.cityId" placeholder="请输入市"  clearable />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="县" prop="countyId">
                <el-input v-model="form.countyId" placeholder="请输入县"  clearable />
              </el-form-item>
            </el-col>               -->
            <el-col>
              <el-form-item label="人员姓名" prop="personName">
                <el-input v-model="form.personName" placeholder="请输入人员姓名"  clearable />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="性别" prop="gender" clearable>
                <el-select v-model="form.gender" placeholder="请选择性别" clearable>
                  <el-option v-for="item in [{label:'男',value:'男'},{label:'女',value:'女'}]" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="电话" prop="tel" required>
                <el-input v-model="form.tel" placeholder="请输入电话"  clearable />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="现场人员类别" prop="category">
                <el-select v-model="form.category" placeholder="请选择现场人员类别" clearable>
                  <el-option v-for="item in option" :key="item.dictItemCode" :label="item.dictItemName" :value="item.dictItemCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <template v-if="title=='新建现场人员'">
              <el-col :span="12">
                <el-form-item label="省" prop="provinceId">
                  <el-select v-model="form.provinceId" placeholder="请选择" @change="chooseFormProvince" style="width: 100%;">
                    <el-option v-for="item in provinceFormData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
              </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="市" prop="cityId">
                  <el-select v-model="form.cityId" placeholder="请选择" @change="chooseFormCity" style="width: 100%;">
                    <el-option v-for="item in cityFormData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="区/县" prop="countyId">
                  <el-select v-model="form.countyId" placeholder="请选择" style="width: 100%;">
                    <el-option v-for="item in areaFormData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>              
            </template>
            <el-col>
              <el-form-item label="现场人员角色（角色可多选）" prop="role">
                <el-checkbox-group v-model="form.role">
                  <el-checkbox v-for="item in option1" :key="item.roleId" :label="item.roleId">{{ item.role }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="现场人员单位" prop="unit">
                <el-input v-model="form.unit" placeholder="请输入现场人员单位"  clearable />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="描述信息" prop="commentInfo">
                <el-input v-model="form.commentInfo" type="textarea" maxlength="500" show-word-limit :autosize="{ minRows: 5, maxRows: 5 }" placeholder="请输入描述信息" clearable/>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="创建人单位" prop="company" required>
                <el-input v-model="form.company" placeholder="请输入创建单位"  disabled />
              </el-form-item>
            </el-col>   
            <el-col>
              <el-form-item label="创建人" prop="createUser" required>
                <el-input v-model="form.createUser" placeholder="请输入创建人"  disabled />
              </el-form-item>
            </el-col>            
            <el-col>
              <el-form-item label="创建时间" prop="createTime" required>
                <el-input v-model="form.createTime" placeholder="请输入创建时间"  disabled />
              </el-form-item>
            </el-col>

        </el-row>         
      </el-form>
      <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="save">保 存</el-button>
              <el-button @click="open = false">取 消</el-button>
          </div>
      </template>
    </el-dialog>          
    
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
        <p></p>
        <el-radio-group v-model="radio">
          <el-radio :label="0" @click="openSelectUser">通过选择系统用户加入</el-radio>
          <el-radio :label="1">通过文件导入</el-radio>
        </el-radio-group>
        <!-- <el-button style="margin:0 20px" :disabled="radio=='0'">导入</el-button> -->
        <p></p>
        <el-table v-if="radio=='0'&&systemUser.length>0" :data="systemUser">
          <el-table-column label="部门" prop="orgName"  show-overflow-tooltip></el-table-column>
          <el-table-column
                  prop="realName"
                  label="人员"
                  show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                  prop="mobile"
                  label="手机号"
                  show-overflow-tooltip
                >
                </el-table-column>
        </el-table>
           <el-upload v-if="radio=='1'" ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload" :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError" :on-success="handleFileSuccess" :data="{'xsemId':currentEvent.id}" :auto-upload="false" drag>
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                 <div class="el-upload__tip text-center">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate('现场人员导入模板.xlsx')">下载模板</el-link>
                 </div>
              </template>
           </el-upload>
           <template #footer>
              <div class="dialog-footer">
                 <el-button type="primary" @click="submitFileForm">确 定</el-button>
                 <el-button @click="upload.open = false">取 消</el-button>
              </div>
           </template>
    </el-dialog>
    <el-dialog v-model="show" width="1200px" append-to-body>
      <p></p>
      <template #title>
        人员选择
        （<span>多选</span>）
         <!--  <span v-show="isshow == 1">单选</span> -->
      </template>
      <select-user ref="selectRef"  @getSelectList="getSelectList" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="ok">确 定</el-button>
          <el-button @click="cancelP">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="fieldPersonnelInformation">
import selectUser from "./selectUser";
import useEventStore from "@/store/modules/event";
import { getAllList, saveData, getDetail, updateData ,getCreateInfo, del, getRoleList ,sysUserImport } from "@/api/comprehensiveInformation/fieldPersonnelInformation.js"
import { getToken } from "@/utils/auth";
import { getDict } from "@/api/system/dict";
import { getProvince, getChildArea, getDivisionCode } from "@/api/system/division";
const currentEvent = computed(() => useEventStore().currentEvent);
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const ids = ref([]);
const radio = ref(1)
const loading = ref(false);
const single = ref(true);
const multiple = ref(true);
const show=ref(false)
const total = ref(0);
const showSearch = ref(true);
const open = ref(false);
const title = ref();
const option = ref([]);
const option1 = ref([]);
const saveRole = ref([]);
const provinceFormData = ref([]);//表单省 
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县
const systemUser=ref([])//导入-系统用户
/*** 导入参数 */
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { token: "token " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/personnelManagement/parseExcel"
});
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        category: undefined,
        personName: undefined,
        tel: undefined,
    },
    form: {
      category:'1'
    },
    rules: {
      personName:[{ required: true, message: "人员姓名不能为空", trigger: "blur" }],
      gender:[{ required: false, message: "性别不能为空", trigger: "change" }],
      tel:[{ required: true, message: "手机号不能为空",trigger: "change"},{
            validator: function(rule, value, callback) {
              if (/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value) == false) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },trigger: "blur"
          }],
      category:[{ required: true, message: "现场人员类别不能为空", trigger: "blur" }],
      provinceId:[{ required: true, message: "省不能为空", trigger: "change" }],
      cityId:[{ required: false, message: "市不能为空", trigger: "change" }],
      countyId:[{ required: false, message: "区不能为空", trigger: "change" }],
      role:[{ required: true, message: "请至少选择一个现场人员角色", trigger: "change" }],
    }
})
const { queryParams, form, rules } = toRefs(data)

/** 获取省列表 */
function getProvinceData() {
  getProvince().then((response) => {
    provinceFormData.value = response.data;
  });
}

function chooseFormProvince(value) {
  form.value.cityId = null;
  form.value.countyId = null;
  cityFormData.value = [];
  areaFormData.value = [];
  getChildArea(value).then(response => {
    cityFormData.value = response.data;
  });
}

function chooseFormCity(value) {
  form.value.countyId = null;
  areaFormData.value = [];
  getChildArea(value).then(response => {
    areaFormData.value = response.data;
  });
}

// 新增
function handleAdd(){
  title.value = '新建现场人员';
  getInfo();
}
function getInfo(){
  getCreateInfo().then(res=>{
    open.value = true;
    proxy.resetForm("addRef");
    form.value = res.data;
    form.value.role=[]
  })
}
// 编辑
function handleEdit(row){
  title.value = '编辑现场人员'
  detail(row.xpimId);
}
// 查看
function detail(id){
  getDetail({id:id}).then(res=>{
    open.value = true;
    proxy.resetForm("addRef");
    form.value = res.data;
    form.value.createUser = res.data.userName;
    saveRole.value = form.value.role.split(',');
    form.value.role = form.value.role.split(',');
  })
}
// 保存
function save(){
  proxy.$refs["addRef"].validate(valid => {
    if (valid) {
      if(title.value=='新建现场人员'){
        form.value.role = form.value.role.join(',');
          saveData({...form.value,xsemId:currentEvent.value.id}).then(res=>{
            proxy.$modal.msgSuccess("新建成功");
            open.value = false;
            getList();
          })
      }else{
        if(saveRole.value){
          let arr = [];
          let arr2= form.value.role;
          saveRole.value.forEach(item=>{
            if(arr2.indexOf(item)== -1) {
              arr.push(item)
            };
          })
          form.value.roleDeletion = arr.join(',')
        }else{
          form.value.roleDeletion = '';
        }
       
        form.value.role = form.value.role.join(',');
        updateData({...form.value}).then(res=>{
          proxy.$modal.msgSuccess("保存成功");
          open.value = false;
          getList();
        })
      }
    }
  })
}

function handleSelectionChange(selection){
  console.log(selection)
  ids.value=selection.map((item) => item.xpimId)
}
// 批量删除
function handleDel(){
  let str=ids.value.join(',')
  proxy.$modal
			.confirm("是否确认删除该信息，请确认是否要删除？", )
			.then(function() {
				return del(str);
			})
			.then(() => {
				getList();
				proxy.$modal.msgSuccess("删除成功");
        proxy.$refs['tableRef'].clearSelection()
			})
			.catch(() => {});
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
			.confirm("是否确认删除该信息，请确认是否要删除？", )
			.then(function() {
				return del(row.xpimId);
			})
			.then(() => {
        getList();
				proxy.$modal.msgSuccess("删除成功");
        
			})
			.catch(() => {});
}

/** 打开人员弹窗 */
function openSelectUser(num) {
  // time.value = new Date().getTime();
  // isshow.value = num;
  show.value = true;

  nextTick(() => {
    proxy.$refs["selectRef"].reset();
    proxy.$refs["selectRef"].getTreeselect();
  });
}
// 提交人员
function ok() {
  show.value = false;
  nextTick(() => {
    proxy.$refs["selectRef"].submit();
  });
}
function getSelectList(val){
  let value = JSON.parse(JSON.stringify(val));
 
  systemUser.value=value
  systemUser.value.forEach((v,i)=>{
    v.tel=v.mobile
    v.personName=v.realName
    v.unit=v.orgName
    v.category='2'
    v.role='25eae82abcc24c6eb15af8b63da824a4'
  })
  
}

/** 关闭人员弹窗 */
function cancelP() {
  show.value = false;
  proxy.$refs["selectRef"].reset();
}

// 模板下载
function importTemplate(name) {
    proxy.downloadTemplate("/template/download", {
        fileName: name
    }, name);
}
/** 提交上传文件 */
function submitFileForm() {
  if(radio.value==1){
    proxy.$refs["uploadRef"].submit();
  }else{
    sysUserImport({xsemId:currentEvent.value.id,userList:systemUser.value}).then(res=>{
    console.log(res)
    if(res.code==200){
      proxy.$modal.msgSuccess("导入成功");
      upload.open=false
      getList()
    }
  })
  }
};

/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    radio.value=1
    upload.open = true;
    systemUser.value=[]
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在上传文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$modal.closeLoading();
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +  response.data?response.data:response.message + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};


/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    dataList.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
}

/** 查询数据列表 */
function getList() {
  if(currentEvent.value){
    loading.value = true;
    getAllList({...queryParams.value,xsemId:currentEvent.value.id}).then(response => {
        dataList.value = response.data.rows ? response.data.rows : [];
        total.value = response.data.total;
        loading.value = false;
    }).catch(err=>{loading.value = false});
  }else{
    dataList.value = [];
    total.value = 0;
  }
}
// 获取人员角色
function getRole(){
  getRoleList().then(res=>{
    option1.value = res.data?res.data:[];
  })
}
/** 获取字典值 */
	async function getDictData() {
		await getDict("rylb").then(response => {
		    option.value = response.data;
		});
	}
	function getType(val){
	  var name = ''
	  option.value.forEach(item => {
			if(item.dictItemCode == val) {
				name = item.dictItemName
				return
			}
		})
		return name
	}
onMounted(() => {
  getRole();
  setTimeout(()=>{
    getList();
    getProvinceData();
  },200)
})
getDictData();
</script>

<style scoped lang="scss">
.title{
  margin: 0 0 20px!important;
}
</style>

